/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.Map;

import com.hiddenequity.adextensions_service.CampaignAdExtensionResponseParser;
import com.hiddenequity.adextensions_service.CampaignAdExtensionService;
import com.hiddenequity.geolocation_service.GeoLocationResponseParser;
import com.hiddenequity.geolocation_service.GeoLocationService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.Country;
import com.hiddenequity.utils.DataValidator;
import com.hiddenequity.utils.LocationDataProvider;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

public class Act_LocationExtensionOperation extends Act_Super{

	private EditText edit_locext_company_name;
	private EditText edit_locext_phone;
	private EditText edit_locext_address_line1;
	private EditText edit_locext_address_line2;
	private EditText edit_locext_city;
	private EditText edit_locext_province;
	private EditText edit_locext_postcode;
	private Spinner spin_locext_country;
	
	private String campaignName;
	
	private String campaignId;
	private String extensionId;
	
	private String countryCode;
	private String companyName;
	private String phoneNumber;
	private String streetAddress;
	private String streetAddress2;
	private String cityName;
	private String provinceName;
	private String postalCode;

	
	private String initCountryCode = "";
	private String initCompanyName = "";
	private String initPhoneNumber = "";
	private String initStreetAddress = "";
	private String initStreetAddress2 = "";
	private String initCityName = "";
	private String initProvinceName = "";
	private String initPostalCode = "";	
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.super_operation_layout);

		((ViewStub) findViewById(R.id.stub_locationextension_operation)).inflate();
		
		Intent intent = getIntent();
		campaignId = intent.getStringExtra("campaignId");
		extensionId = intent.getStringExtra("extensionId");
		campaignName = intent.getStringExtra("campaignName");
		
		countryCode = intent.getStringExtra("countryCode");
		companyName = intent.getStringExtra("companyName");
		phoneNumber = intent.getStringExtra("phoneNumber");
		streetAddress = intent.getStringExtra("streetAddress");
		streetAddress2 = intent.getStringExtra("streetAddress2");
		cityName = intent.getStringExtra("cityName");
		provinceName = intent.getStringExtra("provinceName");
		postalCode = intent.getStringExtra("postalCode");
		
		if(extensionId != null){
			initCountryCode = countryCode == null ? "" : countryCode;
			initCompanyName = companyName == null ? "" : companyName;
			initPhoneNumber = phoneNumber == null ? "" : phoneNumber;
			initStreetAddress = streetAddress == null ? "" : streetAddress;
			initStreetAddress2 = streetAddress2 == null ? "" : streetAddress2;
			initCityName = cityName == null ? "" : cityName;
			initProvinceName = provinceName == null ? "" : provinceName;
			initPostalCode = postalCode == null ? "" : postalCode;
		}
		
		if(extensionId != null){
			title.setText(R.string.title_locationextension_edit);
		} else {
			title.setText(R.string.title_locationextension_add);
		}
		
		
		if(campaignName != null){
			sub_title.setText(campaignName);
		} else {
			sub_title.setVisibility(View.GONE);
		}

		filter.setVisibility(View.GONE);
		
		
		edit_locext_company_name = (EditText) findViewById(R.id.edit_locext_company_name);
		edit_locext_company_name.setText(companyName);
		
		edit_locext_phone = (EditText) findViewById(R.id.edit_locext_phone);
		edit_locext_phone.setText(phoneNumber);
		
		edit_locext_address_line1 = (EditText) findViewById(R.id.edit_locext_address_line1);
		edit_locext_address_line1.setText(streetAddress);
		
		edit_locext_address_line2 = (EditText) findViewById(R.id.edit_locext_address_line2);
		edit_locext_address_line2.setText(streetAddress2);
		
		edit_locext_city = (EditText) findViewById(R.id.edit_locext_city);
		edit_locext_city.setText(cityName);
		
		edit_locext_province = (EditText) findViewById(R.id.edit_locext_province);
		edit_locext_province.setText(provinceName);
		
		edit_locext_postcode = (EditText) findViewById(R.id.edit_locext_postcode);
		edit_locext_postcode.setText(postalCode);
		
		spin_locext_country = (Spinner) findViewById(R.id.spin_locext_country);
    	ArrayList<Country> countryList = LocationDataProvider.getCountryList(getApplication());
    	ArrayList<Country> shortCountryList = new ArrayList<Country>();
    	String[] shortCountryCodeList = getResources().getStringArray(R.array.arr_locationextension_country_list);
    	for(Country country: countryList){
    		for(String code: shortCountryCodeList){
        		if(country.getCode().toLowerCase().equals(code.toLowerCase())){
        			shortCountryList.add(country);
        			break;
        		}
    		}
    	}
    	ArrayAdapter<Country> adapter = new ArrayAdapter<Country>(this,
				android.R.layout.simple_spinner_item,
				shortCountryList);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin_locext_country.setAdapter(adapter);
        ListIterator<Country> countryIterator = shortCountryList.listIterator();
		while(countryIterator.hasNext()){
			String code = countryIterator.next().getCode();
			if(code.equals(countryCode)){
				spin_locext_country.setSelection(countryIterator.nextIndex()-1);
				break;
			}
		} 
		
		
	}

	
    /*
     * Save processing
     */
    public void onClick_saveData(View v){
    	if(isDataValid()){
    		runOperationAsync(OPERATION_PREPARE_DATA, getString(R.string.progress_preparing), false);
    	} else {
    		showOperationError(R.string.msg_title_invalid_data, formErrorString);
    	}
    }//onClick_saveData
	
	
	/*
	 * Check form data before submit
	 */
	private boolean isDataValid(){
		boolean result = true;
		
		countryCode = ((Country)spin_locext_country.getItemAtPosition(spin_locext_country.getSelectedItemPosition())).getCode();
		
		companyName = edit_locext_company_name.getText().toString().trim();
		if(!DataValidator.isName(companyName)){
			result = false;
			formErrorString = "";
		}
		
		phoneNumber = edit_locext_phone.getText().toString();
		
		streetAddress = edit_locext_address_line1.getText().toString().trim();
		
		streetAddress2 = edit_locext_address_line2.getText().toString().trim();
		
		cityName = edit_locext_city.getText().toString().trim();
		
		provinceName = edit_locext_province.getText().toString().trim();
		
		postalCode = edit_locext_postcode.getText().toString().trim();
		
		return result;
	}//isDataValid
	
	
	
	/*
	 * Async operation
	 */
	private void runOperationAsync(final int operation, String message, boolean overlap) {

		//Stop if thread is alive
		if(thread.isAlive() && !overlap)
			return;
		
		//Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		//Check if Internet connection alive
		if(!isConnectionAvalable()){
			progressDialog.dismiss();
			return;
		}

		thread = new Thread(){
			public void run() {
				//Perform authentication
				new AuthService(Act_LocationExtensionOperation.this, getApplication());
				//Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
							case OPERATION_PREPARE_DATA:
								Act_LocationExtensionOperation.this.getGeoLocationData();
								break;
							
							case OPERATION_SET_DATA:
								Act_LocationExtensionOperation.this.locationExtensionAddOperation();
								break;				
								
							case OPERATION_REMOVE_DATA:
								Act_LocationExtensionOperation.this.locationExtensionRemoveOperation();
								break;	
						}
					} catch (Exception e) {
						e.printStackTrace();
						//responseErrorString = "Internal error";
					}
				}
				//Perform postoperation
				Act_LocationExtensionOperation.this.runOnUiThread(new Runnable() {
					public void run() {
						
						progressDialog.dismiss();

						if (AuthService.authToken != null) {
							
							showOperationError(R.string.msg_title_error, responseErrorString);
							
							switch (operation) {
								case OPERATION_PREPARE_DATA:
									if (responseErrorString == null)
										if(isGeoDataAvalable){
											runOperationAsync(OPERATION_SET_DATA, getString(R.string.progress_saving), true);
										} else {
											new AlertDialog.Builder(Act_LocationExtensionOperation.this)
												.setTitle(R.string.msg_title_invalid_data)		
												.setMessage("Cannot find this address.")
												.setPositiveButton(R.string.btn_Ok, null)
												.setCancelable(false)
									    		.create()
									    		.show();
										}
											
									break;
								
								case OPERATION_SET_DATA:
									if (responseErrorString == null)
										runOperationAsync(OPERATION_REMOVE_DATA, getString(R.string.progress_removing), true);
									break;
									
								case OPERATION_REMOVE_DATA:
									if (responseErrorString == null)
										if (isChangesMade) {
											finishActivityWithResult(RESPONSE_REFRESH_REQUIRED);
										} else {
											finishActivityWithResult(RESPONSE_NO_REFRESH_REQUIRED);
										}
									
									break;	
							}
						} else {
							Intent intent = new Intent(Act_LocationExtensionOperation.this.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start(); 		
			
	}//runOperationAsync	

	
	/*
	 * Get Geo location data
	 */
	private Map<String, String> geoLocationData = new HashMap<String, String>();
	private boolean isGeoDataAvalable;
	private void getGeoLocationData(){
		
		//nullateFormData();
		
		String resp = Communication.postSOAP(
				GeoLocationService.URL_GEO_LACATION_SERVICE, 
				GeoLocationService.getGeoLocationData(
						countryCode, 
						companyName, 
						phoneNumber, 
						streetAddress, 
						streetAddress2, 
						cityName, 
						provinceName, 
						postalCode)
    		);
		
    	GeoLocationResponseParser parser = new GeoLocationResponseParser(resp);
    	geoLocationData.putAll(parser.getGeoLocationData());
    	
    	isGeoDataAvalable = parser.isGeoDataReceived();
    	
    	responseErrorString = parser.checkForErrors();
    	
	}//getGeoLocationData
	
	
	
	/*
	 * Remove operation
	 */
	private void locationExtensionRemoveOperation() {
    	if(extensionId == null || !isChangesMade)
    		return;
		
		String resp = Communication.postSOAP(
				CampaignAdExtensionService.URL_CAMPAIGN_AD_EXTENSION_SERVICE, 
				CampaignAdExtensionService.removeLocationAdExtension(extensionId, campaignId)
    		);
		
    	CampaignAdExtensionResponseParser parser = new CampaignAdExtensionResponseParser(resp);
    	responseErrorString = parser.checkForErrors();
	}//locationExtensionRemoveOperation


	
	/*
	 * Add operation
	 */
	private boolean isChangesMade = true;
	
	private void locationExtensionAddOperation() {

		if(initCountryCode.equals(countryCode) && 
				initCompanyName.equals(companyName) && 
				initPhoneNumber.equals(phoneNumber) && 
				initStreetAddress.equals(streetAddress) && 
				initStreetAddress2.equals(streetAddress2) && 
				initCityName.equals(cityName) &&
				initProvinceName.equals(provinceName) && 
				initPostalCode.equals(postalCode)){
			
    		isChangesMade = false;
    		return;
		}
		
//		countryCode = countryCode.equals("") ? null : countryCode;
//		companyName = companyName.equals("") ? null : companyName;
//		phoneNumber = phoneNumber.equals("") ? null : phoneNumber;
//		streetAddress = streetAddress.equals("") ? null : streetAddress;
//		streetAddress2 = streetAddress2.equals("") ? null : streetAddress2;
//		cityName = cityName.equals("") ? null : cityName;
//		provinceName = provinceName.equals("") ? null : provinceName;
//		postalCode = postalCode.equals("") ? null : postalCode;	
		
		String latitudeInMicroDegrees = geoLocationData.get("latitudeInMicroDegrees");
		String longitudeInMicroDegrees = geoLocationData.get("longitudeInMicroDegrees");
		String encodedLocation = geoLocationData.get("encodedLocation");
		
		String resp = Communication.postSOAP(
				CampaignAdExtensionService.URL_CAMPAIGN_AD_EXTENSION_SERVICE, 
				CampaignAdExtensionService.locationExtensionOperation(
						campaignId,
						countryCode,
						companyName,
						phoneNumber,
						streetAddress,
						streetAddress2,
						cityName,
						provinceName,
						postalCode,
						latitudeInMicroDegrees, 
						longitudeInMicroDegrees,
						encodedLocation)
    		);

    	CampaignAdExtensionResponseParser parser = new CampaignAdExtensionResponseParser(resp);
    	responseErrorString = parser.checkForErrors();
	}//locationExtensionOperation

}
